package edu.ssdut.reviseweb.controllers;

import edu.ssdut.revise.api.RefactoringVis;
import edu.ssdut.revise.exceptions.*;
import edu.ssdut.revise.models.VisFragment;
import edu.ssdut.reviseweb.entities.ResData;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("/api")
@CrossOrigin
public class ApiController {
    @GetMapping("/git")
    @ResponseBody
    public ResData<VisFragment> gitApi(@RequestParam("repoIdentifier") String repoIdentifier,
                                       @RequestParam("startCommit") String startCommit,
                                       @RequestParam("endCommit") String endCommit,
                                       @RequestParam("ifLocal") Boolean ifLocal) {
        try {
            VisFragment fragment = new RefactoringVis().getFragmentWithGit(repoIdentifier, startCommit, endCommit, ifLocal);
            return new ResData<>(true, fragment, "");
        } catch (NotExistOrNotDirectoryException e) {
            return failureRes("输入的仓库不存在或非目录！");
        } catch (GitOperationException e) {
            return failureRes("Git操作错误！");
        } catch (NotLegalRepositoryException e) {
            return failureRes("输入的仓库地址非git仓库目录！");
        } catch (IOException e) {
            return failureRes("仓库无法被访问！");
        } catch (IllegalCommitHashException e) {
            return failureRes("提交哈希错误：" + e.getMessage());
        } catch (ParserException e) {
            return failureRes("语法无法被解析器解析：" + e.getMessage());
        }
    }

    @GetMapping("/dir")
    @ResponseBody
    public ResData<VisFragment> gitApi(@RequestParam("originalDir") String originalDir,
                                       @RequestParam("modifiedDir") String modifiedDir) {
        try {
            VisFragment f = new RefactoringVis().getFragment(originalDir, modifiedDir);
            return new ResData<>(true, f, "");
        } catch (NotExistOrNotDirectoryException e) {
            return failureRes("输入的目录不存在或非目录！" + e.getMessage());
        } catch (ParserException e) {
            return failureRes(e.getMessage());
        }
    }

    private ResData<VisFragment> failureRes(String message) {
        return new ResData<>(false, null, message);
    }
}
